package com.music.controller.file;

import com.alibaba.fastjson.JSONObject;
import com.music.config.MinioConfig;
import com.music.dto.utils.OpResultDTO;
import com.music.utils.HttpRequestReader;
import com.music.utils.JWTUtil;
import com.music.utils.file.FileUtil;
import com.music.utils.file.MinioFactory;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

@CrossOrigin
@RestController
@RequestMapping("/api/file")
public class FileController {
    @Resource
    private MinioConfig minioConfig;
    @Resource
    private MinioClient client;
    private final FileUtil fileUtil = new MinioFactory().getFileUtil();
    private final Logger logger = LoggerFactory.getLogger(FileController.class);

    /*
     * @Description 下载图片
     * @Author DY
     * @Date 2021/11/24
     **/
    @GetMapping("/download/image/{fileName}")
    public void downloadImage(@PathVariable("fileName") String fileName, HttpServletResponse httpResponse) {
        if (fileName == null || "null".equals(fileName)) {
           return;
        }
        try {
            GetObjectArgs args = GetObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object("image/"+fileName)
                    .build();
            GetObjectResponse object = client.getObject(args);
            byte[] buf = new byte[1024];
            int length = 0;
            httpResponse.reset();
            httpResponse.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(fileName, "UTF-8"));
            httpResponse.setContentType(object.headers().get("Content-Type"));
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            logger.info("下载失败" + ex.getMessage());
        }
    }

    /*
     * @Description 下载音频
     * @Author DY
     * @Date 2021/11/24
     **/
    @GetMapping("/download/music/{fileName}")
    public void downloadMusic(@PathVariable("fileName") String fileName, HttpServletResponse httpResponse) {
        if (fileName == null || "null".equals(fileName)) {
            return;
        }
        try {
            GetObjectArgs args = GetObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object("music/"+fileName)
                    .build();
            GetObjectResponse object = client.getObject(args);
            byte[] buf = new byte[1024];
            int length = 0;
            httpResponse.reset();
            httpResponse.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(fileName, "UTF-8"));
            httpResponse.setContentType(object.headers().get("Content-Type"));
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            logger.info("下载失败" + ex.getMessage());
        }
    }

    /*
     * @Description 上传文件
     * @Author DY
     * @Date 2021/11/24
     **/
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public OpResultDTO upload(@RequestHeader(name = "Access-Token") String token, HttpServletRequest request) throws Exception {
        OpResultDTO opResultDTO = new OpResultDTO();
        MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
        MultipartFile file = req.getFile("file");
        String type = req.getParameter("type");
        assert file != null;
        String fileName = file.getOriginalFilename();
        try {
            String saveName= JWTUtil.verifyToken(token).getAccountId() + (System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf('.')));
            if (type.equals("music")) {
                fileUtil.upload(file, "music/" + saveName);
            } else if (type.equals("image")) {
                fileUtil.upload(file, "image/" + saveName);
            } else throw new Exception();
            opResultDTO.setMessage("success");
            JSONObject res = new JSONObject();
            res.put("saveName",saveName);
            res.put("size", file.getSize());
            opResultDTO.setResult(res);
            return opResultDTO;
        } catch (Exception e) {
            opResultDTO.setMessage("error");
            System.out.println(fileName + "添加失败");
            return opResultDTO;
        }
    }

    /*
     * @Description 导出音频
     * @Author DY
     * @Date 2021/11/24
     **/
    @RequestMapping(value = "/export/music", method = RequestMethod.POST)
    public void exportMusic(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
        JSONObject jsonRequest = HttpRequestReader.getJsonObject(httpRequest);
        String fileName = jsonRequest.getString("fileName");
        try {
            java.lang.Compiler.disable();
            GetObjectArgs args = GetObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object("music/"+fileName)
                    .build();
            GetObjectResponse object = client.getObject(args);
            byte[] buf = new byte[1024];
            int length = 0;
            httpResponse.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(fileName, "UTF-8"));
            httpResponse.setContentType(object.headers().get("Content-Type"));
            httpResponse.setCharacterEncoding("utf-8");
            OutputStream outputStream = httpResponse.getOutputStream();
            while ((length = object.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception ex) {
            logger.info("下载失败" + ex.getMessage());
        }
    }

    /*
     * @Description 删除文件
     * @Author DY
     * @Date 2021/11/24
     **/
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public OpResultDTO remove(HttpServletRequest request) {
        OpResultDTO op = new OpResultDTO();
        try {
            JSONObject jsonObject = HttpRequestReader.getJsonObject(request);
            String fileName = jsonObject.getString("fileName");
            String type = jsonObject.getString("type");
            fileUtil.remove(fileName, type);
            op.setMessage("success");
            op.setResult("删除成功");
            return op;
        } catch (Exception e) {
            op.setMessage("error");
            op.setResult("删除失败");
        }
        return op;
    }
}
